# coding=utf-8
import logging
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, generate_filter
from common.sms.model import Sms, SMS_STATUS
from common.bankcard import db as bankcard_db
from common import orm
from sqlalchemy import func

_LOGGER = logging.getLogger('hydra')


@sql_wrapper
def get_sms(id):
    return get(Sms, id)


@sql_wrapper
def list_sms(query_dct):
    return list_object(query_dct, Sms)


@sql_wrapper
def get_sms_record_overview(parsed_dct):
    query = orm.session.query(func.sum(Sms.amount))
    query = query.filter(generate_filter(parsed_dct, Sms))
    income = query.filter(Sms.amount > 0).scalar()
    spend = query.filter(Sms.amount < 0).scalar()
    return income, spend


@sql_wrapper
def get_last_sms_transaction_time(phone):
    sms = Sms.query.filter(Sms.phone == phone).order_by(
        Sms.id.desc()).first()
    if sms:
        return sms.transaction_time
    else:
        return None


@sql_wrapper
def get_last_sms_out_id(phone):
    sms = Sms.query.filter(Sms.phone == phone).order_by(
        Sms.id.desc()).first()
    if sms:
        return sms.out_sms_id
    else:
        return 0


def _get_str(s, start, end):
    _LOGGER.info('s>>>>>>>>>>>>>>>%s' % s)
    _LOGGER.info('start>>>>>>>>>>>>>>>%s' % start)
    _LOGGER.info('end>>>>>>>>>>>>>>>%s' % end)
    if start not in s:
        return ''
    else:
        p1 = s.index(start)
        if end not in s[p1:len(s)]:
            return ''
        else:
            p2 = s.index(end, p1 + len(start))
            if p2 > p1:
                return (s[p1 + len(start): p2]).replace(',', '')
            else:
                return ''


# 您尾号5525的储蓄卡账户1月31日13时20分支付机构提现收入人民币199.96元,活期余额2233.39元。[建设银行]
# 您尾号2215的储蓄卡账户2月2日14时26分收费支出人民币7.50元,活期余额31092.41元。[建设银行]
def get_amount_from_content(content):
    if u'收入人民币' in content:
        amount = _get_str(content, u'收入人民币', u'元')
        return which_to_return(amount)
    elif u'转入人民币' in content:
        amount = _get_str(content, u'转入人民币', u'元')
        return which_to_return(amount)
    elif u'交易人民币' in content:
        amount = _get_str(content, u'交易人民币', u'，')
        return which_to_return(amount)
    elif u'存入' in content:
        amount = _get_str(content, u'存入', u'元')
        if u'浦发银行' in content:
            amount = _get_str(content, u'存入', u'[')
        return which_to_return(amount)
    elif u'转入' in content:
        amount = _get_str(content, u'转入', u'元')
        return which_to_return(amount)
    elif any(str_ in content for str_ in (u"提现金额", u"汇入金额")):
        amount = _get_str(content, u'金额', u'元')
        return which_to_return(amount)
    elif u'汇款金额' in content:
        amount = _get_str(content, u'汇款金额', u'元')
        return -which_to_return(amount)
    else:
        amount = _get_str(content, u'支出人民币', u'元')
        return -which_to_return(amount)


def get_balance_from_content(content):
    if any(str_ in content for str_ in (u"建设银行", u"邮储银行", u"光大银行", u"摘要:银联入账")):
        balance = _get_str(content, u'余额', u'元')
        if u'为' in balance :
            balance = _get_str(content, u'余额为', u'元')
    elif u'广发银行' in content:
        balance = _get_str(content, u'账户余额:', u'元')
    elif u'中国农业银行' in content:
        balance = _get_str(content, u'余额', u'。')
    elif u'平安银行' in content:
        balance = _get_str(content, u'余额人民币', u'元')
    else:
        balance = ''
    return which_to_return(balance)


def which_to_return(content):
    if content != '':
        return float(content)
    else:
        return 0.00


def get_bank_name_from_content(content):
    if u'建设银行' in content:
        bank_name = u'建设银行'
    elif u'广发银行' in content:
        bank_name = u'广发银行'
    elif u'农业银行' in content:
        bank_name = u'农业银行'
    elif u'邮储银行' in content:
        bank_name = u'邮储银行'
    elif u'光大银行' in content:
        bank_name = u'光大银行'
    else:
        bank_name = ''
    return bank_name


@sql_wrapper
def insert_sms(info):
    exist = Sms.query.filter(Sms.content == info['msg']).filter(Sms.from_phone == info['from_phone']).first()
    if exist:
        _LOGGER.info(u'sms_record_repeat, %s', info['msg'])
        return
    bank_card = bankcard_db.get_bankcard_by_phone(info['phone'], get_bank_name_from_content(info['msg']))
    if bank_card is None:
        return
    sms = Sms()
    sms.out_sms_id = info['id']
    sms.bankcard_name = bank_card.name
    sms.mch_id = bank_card.mch_id
    sms.content = info['msg']
    sms.bank = get_bank_name_from_content(info['msg']) if get_bank_name_from_content(
        info['msg']) != '' else bank_card.bank
    sms.phone = info['phone']
    sms.from_phone = info['from_phone']
    sms.amount = get_amount_from_content(info['msg'])
    sms.balance = get_balance_from_content(info['msg'])
    sms.sms_time = info['time']
    sms.save()
    bankcard_db.update_bankcard_balance(bank_card.name, sms.balance)
    return sms.id


@sql_wrapper
def match_sms(sms_id, order_id, remark='manual'):
    sms = Sms.query.filter(Sms.id == sms_id).filter(
        Sms.status == SMS_STATUS.UNMATCH).first()
    if not sms:
        return
    sms.order_id = int(order_id)
    sms.status = SMS_STATUS.MATCHED
    sms.remark = remark
    sms.save()


@sql_wrapper
def get_unmatch_sms(sms_id):
    return Sms.query.filter(Sms.id == int(sms_id)).filter(
        Sms.status == SMS_STATUS.UNMATCH).first()
